package com.tencent.qcloud.qiaoqiao.ui.net;

import android.app.Activity;
import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tencent.qcloud.qiaoqiao.ui.tools.Constant;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ActivityUtils;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ToastUtils;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.Utils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.tencent.qcloud.qiaoqiao.common.utils.TCConstants.APP_SVR_URL;

/**
 * Created by qian on 2018/8/28.
 */

public class HttpRequest {

    private static final String URL = "http://203.195.167.72:8001/";


    public static void requestHttpData(final Context context, String type, String url, Map<String,Object> requestParameter, final HttpResultListener resultListener){
        OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
        mBuilder.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间

        RequestBody requestBody = null;
        if (requestParameter!=null){
            String postJson = com.alibaba.fastjson.JSONObject.toJSONString(requestParameter);
            requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8") , postJson);
        } else {
            requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"),"");
        }
        Request.Builder builder = new Request.Builder()
                    .addHeader("Content-Type","application/json")
                    .addHeader("x-api-token","6Couxh6yvjH4g1UL")
                    .addHeader("X-Api-Serverid","80")
                    .addHeader("x-api-tenantId","T001273").url(url);
        Request request = null;
        request = builder.post(requestBody).build();

        OkHttpClient client = mBuilder.build();
        Call call = client.newCall(request);
        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Activity a =  (Activity)context;
                a.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        resultListener.onFailure("请求错误");
                    }
                });
                System.out.println("--------------onFailure--------------" + e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String responseStr = response.body().string();

                final com.alibaba.fastjson.JSONObject object = JSON.parseObject(responseStr);
                final boolean result = object.getBoolean("result");
                Activity a = (Activity)context;
                a.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                    if (result){
                        if (object.get("data")==null){
                            resultListener.onSuccess("成功");
                        } else {
                            resultListener.onSuccess(object.get("data").toString());
                        }
                    } else {
                        String message = object.getString("message");
                        resultListener.onFailure(message);
                        ToastUtils.showShort(message);
                    }
                        }
                });
            }
        });
    }

    public static void requestGet(String url,final HttpResultListener httpResponse){
        OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
        mBuilder.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间
//        mBuilder.sslSocketFactory(createSSLSocketFactory());
//        mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        String urlStr =url;
        Request request = new Request.Builder()
                .addHeader("Content-Type","application/json")
                .addHeader("charset","utf-8/json")
                .get().url(urlStr).build();
        OkHttpClient client = mBuilder.build();
        Call call = client.newCall(request);

        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("--------------onFailure--------------" + e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Activity a =  ActivityUtils.getTopActivity();
                final String responseStr = response.body().string();
                a.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(responseStr);
                        httpResponse.onSuccess(responseStr);
                    }
                });
            }
        });
    }

    public static void requestPost(String cmd, RequestBody formBody, final HttpResultListener httpResponse){
        OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
        mBuilder.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间
//        mBuilder.sslSocketFactory(createSSLSocketFactory());
//        mBuilder.hostnameVerifier(new TrustAllHostnameVerifier());
        //构造Request对象
        //采用建造者模式，链式调用指明进行Get请求,传入Get的请求地址
        String urlStr = APP_SVR_URL+cmd;
        if (formBody==null){
           formBody = new FormBody.Builder().build();
        }
        Request request = new Request.Builder()
                .addHeader("Content-Type","application/json")
                .addHeader("charset","utf-8/json")
                .post(formBody).url(urlStr).build();
        OkHttpClient client = mBuilder.build();
        Call call = client.newCall(request);

        //异步调用并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("--------------onFailure--------------" + e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Activity a =  ActivityUtils.getTopActivity();
                final String responseStr = response.body().string();
                a.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(responseStr);
                        int result = object.getInteger("code");
                        if (result==200){
                            httpResponse.onSuccess(object.get("data").toString());
                        } else {
                            String message = object.getString("message");
                            httpResponse.onFailure(message);
                        }
                    }
                });
            }
        });
    }

}
